package com.icloud.wallet.boot.config;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class BNBConfig {
    @Value("${web3j.client-address.bnb}")
    private String rpc;

    @Bean
    public Web3j web3Client() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(30*1000, TimeUnit.MILLISECONDS);
        builder.writeTimeout(30*1000, TimeUnit.MILLISECONDS);
        builder.readTimeout(30*1000, TimeUnit.MILLISECONDS);

        OkHttpClient httpClient = builder.build();
        Web3j web3j = Web3j.build(new HttpService(rpc,httpClient,false));
        String version = "";
        try {
            Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
            version = web3ClientVersion.getWeb3ClientVersion();
            log.info("连接BNB节点成功，地址:{},版本为:{}",rpc, version);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("连接BNB节点异常");
        }
        return web3j;
    }
}
